<template>
  <view class="page page-aftersale-address ui-form-basic">
    <view class="page-address-header">
      <view class="page-address-title">
        <fui-text text="商家退货地址" size="32" color="#333" fontWeight="bold"></fui-text>
        <fui-text text="在此处填写或选择已有退货地址" size="24" color="#999"></fui-text>
      </view>
      <fui-text :text="checkedAddress ? '更换地址' : '选择地址'" size="24" color="var(--fui-color-primary)" fontWeight="bold" @click="handleSelectAddress"></fui-text>
    </view>
    <fui-form ref="formRef" :model="form" class="form-wrapper" labelWidth="200" labelSize="28" labelWeight="bold">
      <fui-form-item label="收货人姓名" prop="name" left="0" marginTop="14" :padding="['16rpx', 0]">
        <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请输入收货人姓名" v-model="form.name"></fui-input>
      </fui-form-item>
      <fui-form-item label="手机号" prop="mobile" left="0" marginTop="14" :padding="['16rpx', 0]">
        <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请输入手机号" v-model="form.mobile"></fui-input>
      </fui-form-item>
      <fui-form-item label="所在地区" prop="areaName" left="0" marginTop="14" :padding="['16rpx', 0]" @click="onShowAreaPicker" arrow>
        <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请选择所在地区" v-model="form.areaName" disabled></fui-input>
      </fui-form-item>
      <fui-form-item label="详细地址" prop="detailAddress" left="0" marginTop="14" :padding="['16rpx', 0]">
        <template v-slot:vertical>
          <fui-textarea size="28" :maxlength="100" height="64rpx" :isCounter="true" radius="16" borderColor="#DFDFDF" v-model="form.detailAddress" placeholder="请输入详细地址" textareaBorder></fui-textarea>
        </template>
      </fui-form-item>
    </fui-form>

    <view class="page-btn-wrapper">
      <fui-button class="primary plain" text="取消" @click="tab.navigateBack" height="78rpx" radius="8rpx"></fui-button>
      <fui-button class="primary" text="确认" :loading="isLoading" :disabled="isLoading" @click="handleSubmit" height="78rpx" radius="8rpx"></fui-button>
    </view>

    <!-- 所在地区 -->
    <fui-picker layer="4" :options="regionData" :linkage="true" :show="showAreaPicker" @change="onChangeArea" @cancel="showAreaPicker = false" :fields='["name","id","children"]'></fui-picker>
  </view>
</template>

<script setup>
import { ref, computed, inject } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { useStore } from 'vuex'
import systemApi from '@/api/system'
import addressApi from '@/api/address'

const store = useStore();
const tab = inject('$tab')
const modal = inject('$modal')

const addressId = ref('')
onLoad((option) => {
  addressId.value = option.addressId || '001'
  // getAddressDetail()

  if (store.getters.regionData.length) {
    regionData.value = store.getters.regionData
  } else {
    getRegionData()
  }
})

const checkedAddress = ref(null)
onShow(() => {
  uni.$once('onCheckedAddress', data => {
    checkedAddress.value = data || null
    form.value = data
  })
})

// 表单信息
const formRef = ref(null)
let form = ref({})
const rules = [
  {
    name: 'name',
    rule: ['required'],
    msg: ["请输入收货人姓名"]
  },
  {
    name: 'mobile',
    rule: ['required', 'isMobile'],
    msg: ['请输入手机号', '请输入正确的手机号']
  },
  {
    name: 'areaName',
    rule: ['required'],
    msg: ['请选择所在区域']
  },
  {
    name: 'detailAddress',
    rule: ['required'],
    msg: ['请输入详细地址']
  }
]

// 获取退货地址数据
const getAddressDetail = async () => {
  try {
    const { data } = await addressApi.getAddressDetail(addressId.value)
    form.value = data || {}
  } catch (err) {
    modal.msgError(err.msg || '获取退货地址详情失败！')
  }
}

// 行政区划数据
const regionData = ref([])
const getRegionData = () => {
  systemApi.administration().then((res) => {
    if (res.code == 0) {
      regionData.value = res.data
    }
  })
}
if (store.getters.regionData.length) {
  regionData.value = store.getters.regionData
} else {
  getRegionData()
}

// 选择所在地区
const showAreaPicker = ref(false)
const onShowAreaPicker = () => {
  showAreaPicker.value = true
}
const onChangeArea = (e) => {
  showAreaPicker.value = false
  form.value.areaId = e.value[3]
  form.value.areaName = e.result
}

// 跳转选择退货地址
const handleSelectAddress = () => {
  tab.navigateTo(`/pages/address/index?isSelector=1&addressId=${addressId.value}`)
}

// 提交表单
const isLoading = ref(false)
const submitApiUrl = computed(() => addressId.value ? 'updateAddress' : 'addAddress')
const handleSubmit = async () => {
  const validRes = await formRef.value.validator(form.value, rules)
  if (validRes.isPassed) {
    isLoading.value = true
    addressApi[submitApiUrl.value](form.value).then(res => {
      isLoading.value = false
      modal.msgSuccess('退货地址保存成功！')
      tab.navigateBack()
    }).catch(err => {
      isLoading.value = false
      modal.msgError('退货地址保存失败！')
    })
  }
}
</script>

<style lang="scss" scoped>
@import "@/static/scss/form.scss";

.page-aftersale-address {
  .page-address-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    .page-address-title {
      .fui-text__wrap {
        display: block;
      }
    }
  }
}
</style>
